package dd.view;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import dd.model.Event;

public class DrawingCanvas extends Canvas {

	Point mousePressed;
	Point mouseReleased;
	ArrayList<Double> choicesAxisX = new ArrayList();
	
	Event event;
	
	public DrawingCanvas (Event event) {
		this.event = event;
	}
	
	public void paint(Graphics g)
	{
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, getWidth(), getHeight());
		
		g.setColor(Color.BLACK);
		int choiceCount = 4;
		int panelWidth = getWidth();
		
		g.drawString("Event Name", panelWidth/2 -10, 10);

		
		int lineGap = (panelWidth -40 ) / choiceCount;

		int linePosX = getX();
		int lineLength = 150;
		int horizationalPos = getY() + 50;

		for (int i = 0; i < 4; i++)
		{
			linePosX = linePosX + lineGap;
			g.drawRect(linePosX -25 , horizationalPos -30, 60, 20);
			g.drawString("Choice "+ i, linePosX -20 , horizationalPos -15);
			g.drawLine(linePosX, horizationalPos, linePosX, horizationalPos + lineLength);
			g.drawString("Result "+ i, linePosX-15, horizationalPos + lineLength + 15);
			choicesAxisX.add((double)linePosX);
		}
	}

	public void update(Graphics g)
	{
		g.setColor(Color.white);
		g.fillRect(0, 0, getWidth(), getHeight());
	}

	public void regesiterMouseEvent()
	{
		addMouseListener(new MouseAdapter()
		{
			public void mousePressed(MouseEvent arg)
			{
				mousePressed = arg.getPoint();
			}
		});
		addMouseListener(new MouseAdapter()
		{
			public void mouseReleased(MouseEvent arg)
			{
				mouseReleased = arg.getPoint();
				paintEdge(mousePressed,mouseReleased);
			}
		});
	}
	
	public void paintEdge(Point x, Point y)
	{
		Graphics g = this.getGraphics();
		Point start = adjustPointAxisX(x);
		Point end = adjustPointAxisX(y);

		g.drawLine((int)start.getX(), (int)start.getY(), (int)end.getX(), (int)start.getY());
	}

	private Point adjustPointAxisX(Point x)
	{
		double delta = Integer.MAX_VALUE;
		Point retval = (Point) x.clone();
		for (int i = 0; i < choicesAxisX.size(); i++)
		{
			if(delta > Math.abs(choicesAxisX.get(i) - x.getX()))
			{
				delta =  Math.abs(choicesAxisX.get(i) - x.getX());
				retval.setLocation(choicesAxisX.get(i), retval.getY());
			}
		}	
		return retval;
	}
}
